package controllers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"short-link/internal/models"
	"short-link/internal/services"
)

type UrlController struct {
	urlService services.URLService
	baseURL    string
}

func NewUrlController(urlService services.URLService, baseURL string) *UrlController {
	return &UrlController{
		urlService: urlService,
		baseURL:    baseURL,
	}
}

func (uc *UrlController) Add(c *gin.Context) {
	var dto models.UrlAddDto
	err := c.ShouldBind(&dto)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	url, err := uc.urlService.CreateURL(c.Request.Context(), dto)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	shortUrl := uc.baseURL + "/" + url.CustomCode
	expiresAt := url.ExpiresAt.Format("2006-01-02 15:04:05")
	c.JSON(http.StatusCreated, models.UrlAddVo{
		ShortURL:  shortUrl,
		ExpiresAt: expiresAt,
	})
}

func (uc *UrlController) RedirectURL(c *gin.Context) {
	shortCode := c.Param("code")
	url, err := uc.urlService.GetURL(c.Request.Context(), shortCode)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if url == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "url not found"})
		return
	}
	c.Redirect(http.StatusMovedPermanently, url.OriginalUrl)
}

func (uc *UrlController) SayHello(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{"health": "Hello"})
}
